package com.kaikeba.estack.common.util;

import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.impl.DefaultMapperFactory;

import java.util.List;

/**
 * bean操作工具类，支持以下几种类型的属性复制
 * map -> bean
 * bean -> bean
 * bean -> map
 *
 * @Auth xingwan
 * @Date 2020/9/8 0:36
 **/
public class BeanUtil {

    private static final MapperFactory MAPPER_FACTORY = new DefaultMapperFactory.Builder().build();

    private final static MapperFacade MAPPER_FACADE = MAPPER_FACTORY.getMapperFacade();

    /**
     * 将S类型对象转换为T类型
     *
     * @param sourceObject 源对象
     * @param tClass       目标对象类型
     * @param <D>
     * @param <S>
     * @return
     */
    public static <S, D> D convert(S sourceObject, Class<D> tClass) {
        return MAPPER_FACADE.map(sourceObject, tClass);
    }


    /**
     * @param sourceObject
     * @param tClass
     * @param mappingContext
     * @param <S>
     * @param <D>
     * @return
     */
    public static <S, D> D convert(S sourceObject, Class<D> tClass, MappingContext mappingContext) {
        return MAPPER_FACADE.map(sourceObject, tClass, mappingContext);
    }

    /**
     * 将S对象属性复制到目标对象属性中
     *
     * @param sourceObject
     * @param targetObject
     * @param <S>
     * @param <D>
     */
    public static <S, D> void convert(S sourceObject, D targetObject) {
        MAPPER_FACADE.map(sourceObject, targetObject);
    }

    /**
     * 将S对象属性复制到目标对象属性中
     *
     * @param sourceObject
     * @param targetObject
     * @param mappingContext
     * @param <S>
     * @param <D>
     */
    public static <S, D> void convert(S sourceObject, D targetObject, MappingContext mappingContext) {
        MAPPER_FACADE.map(sourceObject, targetObject, mappingContext);
    }

    /**
     * 将S对象类型的集合转换为D类型的List集合
     *
     * @param source
     * @param tClass
     * @param <S>
     * @param <D>
     * @return
     */
    public static <S, D> List<D> mapAsList(Iterable<S> source, Class<D> tClass) {
        return MAPPER_FACADE.mapAsList(source, tClass);
    }


    /**
     * 将S对象类型的集合转换为D类型的List集合
     *
     * @param source
     * @param tClass
     * @param <S>
     * @param <D>
     * @return
     */
    public static <S, D> List<D> mapAsList(Iterable<S> source, Class<D> tClass, MappingContext mappingContext) {
        return MAPPER_FACADE.mapAsList(source, tClass, mappingContext);
    }


}
